package com.jt.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

//封装ObjectMapper，转换对象为json，的工具类
public class ObjectMapperUtil {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    // 对象转为json
    public static String toJson(Object object) {
        try {
            return MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    // json转为对象
    public static <T> T toObject(String json, Class<T> targetClass) {
        try {
           return MAPPER.readValue(json, targetClass);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
